<?php
namespace app;

use \GatewayWorker\Lib\Gateway;
use \app\model\User;
use \app\model\Games;
use \app\model\Finance;
use \app\model\UserToRoom;
use \app\model\Rooms;
use \app\model\Message;
use Workerman\Lib\Timer;
class Events
{

    public static function onWorkerStart($businessWorker)
    {

        echo "WorkerStart\n";
        Timer::add(15, function(){
            //echo "timerStart\n";
            $game = Games::where('status',0)->find();
            if(!$game){
              /*
              $user = User::where('avatar','LIKE','http://%')->find();
              if($user){
                  echo "执行更新头像\n";
                  $file_name = md5($user['id'].$user['openid']).'.jpg';
                  $file_path = '/home/gitproject/HBServer/public/static/wxavatar/'.$file_name;
                  try {
                      file_put_contents($file_path,file_get_contents($user['avatar']));
                      $user->avatar = 'https://ling.cash/static/wxavatar/'.$file_name;
                      $user->save();
                  }catch (\Exception $e) {
                      
                  }
              }*/
              return;
            }
            $timeIv = $game['overdue_time'] + $game['create_time'] -time();
            $timeIv = $timeIv<1?mt_rand(15,20):$timeIv;

            echo "游戏:{$game['id']} 定时:{$timeIv}\n";
            Timer::add($timeIv, array('\app\Events', 'settleGame'), [$game['id']], false);

            $game->status=1;
            $game->save();

            //Timer::add(10, array($mail, 'send'), array($to, $content), false);
            //self::settleGame(80);
        });
    }
    public static function onConnect($client_id)
    {
        echo "$client_id 已连接\r\n";
        //Gateway::sendToClient($client_id, "Hello $client_id\r\n");
        //Gateway::sendToAll("$client_id 已连接\r\n");
    }

    public static function onWebSocketConnect($client_id, $data)
    {
        if (!isset($data['get']['token'])) {
            var_dump($data);
            print_r("提出未授权用户\n");
            return Gateway::closeClient($client_id);
        }
        $user = User::where('access_token',$data['get']['token'])->find();
        if(!$user){
            print_r("{$data['get']['token']}用户验证失败\n");
            return Gateway::closeClient($client_id);
        }
        print_r("用户{$user['nickname']}上线,");
        /*
        if($user['last_login_time']==0){
            //保存微信图片
            //$avatar = 'static/wxavatar/'.md5($res['openid']).'.jpg';
            //file_put_contents($avatar,file_get_contents($res['headimgurl']));
            //$user->avatar = $avatar;
        }*/
        $user->last_login_time=time();
        $user->login_ip=$_SERVER['REMOTE_ADDR'];
        $user->save();

        $_SESSION['uid'] = $user->id;
        Gateway::bindUid($client_id,$user->id);//绑定用户
        //$roomList = UserToRoom::where('uid',$user['id'])->select();
        $roomList = UserToRoom::alias('a')->where('uid',$user['id'])->field('rid,coins,title,avatar,creator as cid,gonggao,create_time,expire_time,is_jinyan')->join('rooms r','a.rid = r.id')->select();
        foreach ($roomList as $key => $value) {
            $roomList[$key]['creator'] = User::where('id',$value['cid'])->field('nickname,avatar')->find();
            $roomList[$key]['memberList'] = UserToRoom::alias('a')->join('user','a.uid = user.id')->where('rid',$value['rid'])->field('a.uid,a.coins,a.addtime,user.nickname,user.avatar')->order('a.addtime desc')->select();
        }
        //var_dump($roomList);
        $replayData['cmd']='initRoomList';
        $replayData['data']=$roomList;
        Gateway::sendToClient($client_id,json_encode($replayData));
        print_r("发送房间列表,");
        $msgList=[];
        foreach ($roomList as $key => $value) {
            Gateway::joinGroup($client_id,$value['rid']);//加入群组
            $messages=Message::where('rid',$value['rid'])->order('id', 'desc')->limit(30)->column('msg');
            $msgList['r'.$value['rid']]=$messages;
        }
        $replayData['cmd']='msgList';
        $replayData['data']=$msgList;
        Gateway::sendToClient($client_id,json_encode($replayData));
        print_r("发送消息列表\n");
    }

    public static function onMessage($client_id, $message)
    {
        $msg=json_decode($message,true);
        if(!isset($msg['cmd'])){
            return;
        }
        if($msg['cmd']=='ping'){
          //print_r("{$_SESSION['uid']}发送ping,");
          Gateway::sendToClient($client_id,'{"cmd":"pong"}');
          return;
        }
        //echo $message."\n";
        //如果是聊天信息
        if($msg['cmd']=='chat' && isset($msg['data']['rid']) ){
          $roomInfo = Rooms::where('id',$msg['data']['rid'])->find();

          if($roomInfo['expire_time'] <time()){//群已到期
            $MessageObject=[
              '_id'=>uniqid(),
              'rid'=>$msg['data']['rid'],
              'createdAt'=>time()*1000,
              'text'=>'群已到期,无法发言',
              'system'=> true,
            ];
            $replayData['cmd']='chat';
            $replayData['data']=$MessageObject;
            Gateway::sendToClient($client_id,json_encode($replayData));//发送消息
            return;
          }

          if($roomInfo['is_jinyan']==1 && $roomInfo['creator']!=$_SESSION['uid'] ){//群已禁言
            $MessageObject=[
              '_id'=>uniqid(),
              'rid'=>$msg['data']['rid'],
              'createdAt'=>time()*1000,
              'text'=>'当前群已全体禁言，暂无法聊天',
              'system'=> true,
            ];
            $replayData['cmd']='chat';
            $replayData['data']=$MessageObject;
            Gateway::sendToClient($client_id,json_encode($replayData));//发送消息
            return;
          }


          Gateway::sendToGroup($msg['data']['rid'],$message);
          Message::create(['rid'=>$msg['data']['rid'],'msg'=>json_encode($msg['data']) ]);
          return;
        }
    }
   
   /**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
    public static function onClose($client_id)
    {
        echo "$client_id 已退出\r\n";
    }

   //结算未抢完红包
    public static function settleGame($gid){
      echo "settleGame: $gid\n";
      $gameInfo = Games::get($gid);
      if(!$gameInfo || $gameInfo['status']==2){
        echo "游戏已结算\n";
        return;
      }
      $backMoney=array_sum(json_decode($gameInfo['rand_coins'],true));
      if($backMoney >0){
        //添加财务记录
        $finance = ['uid' => $gameInfo['uid'],'rid' => $gameInfo['rid'],'gid' => $gameInfo['id'],'coins'=>$backMoney,'type'=>3,'addtime'=>time(),];
        Finance::create($finance);
        //给用户加积分
        $userInRoom = UserToRoom::where(['uid'=>$gameInfo['uid'],'rid'=>$gameInfo['rid']])->find();
        $userInRoom->coins += $backMoney;
        $userInRoom->save();

        $MessageObject=[
            '_id'=>uniqid(),
            'rid'=>$gameInfo['rid'],
            'createdAt'=>time()*1000,
            'text'=>'您的未抢完红包已退还',
            'system'=> true,
        ];
        //Message::create(['rid'=>$gameInfo['rid'],'msg'=>json_encode($MessageObject) ]);
        $replayData['cmd']='chat';
        $replayData['data']=$MessageObject;
        Gateway::sendToUid($gameInfo['uid'],json_encode($replayData));//发送消息

        $memberList = UserToRoom::alias('a')->join('user','a.uid = user.id')->where('rid',$gameInfo['rid'])->field('a.uid,a.coins,a.addtime,user.nickname,user.avatar')->order('a.addtime desc')->select();
        $replayData['cmd']='updateMemberList';
        $replayData['data']=['rid'=>$gameInfo['rid'],'memberList'=>$memberList];
        echo "{$gameInfo['rid']}\n";

        Gateway::sendToGroup($gameInfo['rid'], json_encode($replayData));

        $replayData['cmd']='updateSelfCoins';
        $replayData['data']=['rid'=>$gameInfo['rid'],'coins'=>$userInRoom->coins ];
        Gateway::sendToUid($gameInfo['uid'], json_encode($replayData));


      }
      //更新状态
      $gameInfo->status=2;
      $gameInfo->settle_time=time();
      $gameInfo->save();
    }
}
